package com.cysyz.commonservice.mycommonservice.impl;

import java.lang.reflect.Field;

import com.cysyz.commonservice.mycommonservice.BaseService;
import com.cysyz.commonservice.mycommonservice.RegisteService;
import com.cysyz.commonservice.mycommonservice.exception.UserIDExistException;
import com.cysyz.commonservice.mycommonservice.support.Registeable;
import com.cysyz.utils.MD5;

public class RegisteServiceImpl extends BaseService implements RegisteService{
	@Override
	public void registe(Registeable entity) throws UserIDExistException {
		if (isExist(entity.getClass(), entity.getId().trim())) {
			throw new UserIDExistException("the user with this id is already exist:id=" + entity.getId());
		} else {
			Field[] fields = entity.getClass().getDeclaredFields();
			for (Field field : fields) {
				trimValueIfString(entity, field);
			}
			entity.setPassword(MD5.MD5Encode(entity.getPassword()));
			dao.save(entity);
		}
	}

	private void trimValueIfString(Registeable entity, Field field) {
		if(field.getType() == String.class) {
			if (!field.isAccessible()) {
				field.setAccessible(true);
			}
			try {
				field.set(entity, field.get(entity).toString().trim());
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
}
